<template>
  <div>
    <div @click="openDialog">
      <slot name="openDialog" ></slot>
    </div>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
      <div
          class="list_content"
          v-loading="isDisable"
          element-loading-text="资源解析中..."
      >
        <uploader
            :options="options"
            :autoStart="false"
            ref="uploader"
            class="uploader-example"
            @file-added="onFileAdded"
            @file-success="onFileSuccess"
            @file-progress="onFileProgress"
            @file-error="onFileError"
        >
          <uploader-btn ref="uploadBtn" id="global-uploader-btn" :attrs="attrs">
            <div>
              <div class="flexWithJusCenter">
                <i class="el-icon-upload uploadIcon"></i>
              </div>
              <div>
                <!-- <span class="upload-title">将文件拖到此处，或</span> -->
                <span class="upload-subtitle">点击上传</span>
              </div>
            </div>
          </uploader-btn>
          <uploader-unsupport style="margin-bottom: 20px"></uploader-unsupport>
          <uploader-list></uploader-list>
        </uploader>
      </div>
	  <div class="uoload-button">
		  <el-button>取消</el-button>
		  <el-button type="primary" @click="uploadSave">确定</el-button>
	  </div>
    </el-dialog>
  </div>
</template>
<script>
var resourceId = ""; //保存资源id
import md5 from 'js-md5';
import {getToken} from '@/utils/auth'

export default {
  name: "imageUpload",
  props: {},
  watch: {},
  computed: {},
  data() {
    return {
      dialogVisible: false,
      isDisable: false,
      isUploading: false,
      pauseFlag: true,

      options: {
        target: process.env.VUE_APP_BASE_API + "/app/file/uploadBigFile",
        headers: {'Authorization': 'Bearer '+getToken()},
        testChunks: false, //是否开启服务器分片校验
        maxChunkRetries: 5, //最大自动失败重试上传次数
        chunkSize: 3 * 1024 * 1024, //分片大小
        singleFile: true, //单文件上传
        simultaneousUploads: 1,

        processParams(params) {
          //每一次分片传给后台的参数，params是该方法返回的形参，包含分片信息
          return {
            //返回一个对象，会添加到每一个分片的请求参数里面
            name: params.filename,
            code: params.identifier,
            total: params.totalChunks,
            index: params.chunkNumber,
            resourceId,
          };
        },
      },

      attrs: {
        accept: "",
        // accept: ".zip",
      },
    };
  },
  created(){
  },
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },

    //文件添加时回调，这里可以做格式校验，md5计算
    onFileAdded(file) {
      let _this = this
      console.log('onFileAdded--', file);
      let typeName = file.file.name;
      let reg = /\.zip$/;
      // if (!reg.test(typeName)) {
      //   file.ignored = true;
      //   this.$alert("上传文件格式不正确，请检查", "上传错误", {
      //     confirmButtonText: "确定",
      //     callback: (action) => {},
      //   });
      // } else {
      // 计算MD5;
      this.computeMD5(file, _this);
      // }
    },
    //所有分片上传完成的回调，需要注意的是，由于异步上传，每一次分片上传不会等上一次响应回来才发送，
    //因此该上传成功的回调时，返回的分片响应可能不是最后一片，因此后续会发送合并请求告诉后台进行合并文件
    onFileSuccess(rootFile, file, message, chunk) {
      console.log('onFileSuccess--', rootFile, file, message, chunk);
      if (chunk.xhr.status == 200) {
        this.dialogVisible = false;
        let data = {
          name: file.name,
          url: message
        }
        this.$emit("returnUrl", data)
      }
      //所有分片上传成功，发送合并分片请求，具体参数与后台确定，后台合并文件
    },

    //文件上传的过程中会频繁调用该函数
    onFileProgress(rootFile, file, chunk) {
      console.log('onFileProgress--', rootFile, file, chunk);
    },

    //文件上传出错的回调
    onFileError(rootFile, file, msg, chunk) {
      console.log('onFileError--', rootFile, file, msg, chunk);
    },

    computeMD5(file, _this) {
      // let that = this;
      let fileReader = new FileReader();
      let md5Name = "";
      file.pause(); //先暂停，后续生成uniqueIdentifier
      fileReader.readAsArrayBuffer(file.file);

      fileReader.onload = (e) => {
        console.log('e--', e);
        if (file.size != e.target.result.byteLength) {
          _this.$message.error("文件读取失败");
          return;
        }

        md5Name = md5(file.name); //业务需求以文件名作为加密
        file.uniqueIdentifier = md5Name;

        if (md5Name != "") {
          file.resume(); //继续上传文件
        }
      };
      console.log('fileReader--', fileReader);
      fileReader.onerror = function () {
        _this.$message.error("文件读取失败");
      };
    },

    cancelAddRes() {
    },

    continueAddRes() {
    },
	// 将数据返回父组件
	uploadSave(){
		console.log('点击保存')
		this.$emit('uploadSave1')
	}
  },
};
</script>
<style scoped>
.uploader-btn {
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  width: 100%;
  height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.uploader-btn:hover{
  background-color: white;
  border-color: #2C7EF8;
}

.uploadIcon {
  font-size: 67px;
  color: #c0c4cc;
  line-height: 50px;
  margin-bottom: 10px;
  font-weight: 400;
}

.upload-title{
  color: #606266;
  font-size: 14px;
  text-align: center;
  font-weight: 400;
}

.upload-subtitle{
  font-size: 14px;
  text-align: center;
  color: #409eff;
  font-weight: 400;
}

.uploader-list{
  margin-bottom: 10px;
}

/deep/ .uploader-file{
 border-bottom:1px solid white !important;
}

.uoload-button{
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
	margin-bottom: 10px;
}
</style>

